package cc.rengu.redp.bizimpl.igas.controller;


import cc.rengu.redp.bizimpl.bean.LabelValueBean;
import cc.rengu.redp.bizimpl.enums.IgasYesOrNoEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.enums.SettleAccTypeEnum;
import cc.rengu.redp.bizimpl.igas.domain.PDstChannelInfo;
import cc.rengu.redp.bizimpl.igas.domain.PDstTxnAuthCfg;
import cc.rengu.redp.bizimpl.igas.service.PDstChannelInfoService;
import cc.rengu.redp.bizimpl.igas.service.PDstTxnAuthCfgService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpOrganizationService;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.RedpUpmpUtil;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.exception.RedpException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-09
 */
@Slf4j
@Api(tags = "产品管理:支付通道管理")
@RestController
@RequestMapping("/admin/igas/pDstTxnAuthCfg")
public class PDstTxnAuthCfgController  extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(PDstChannelInfoController.class);
    //    @Autowiredyarn
//    private AuthPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private PDstChannelInfoService pDstChannelInfoService;
    @Autowired
    private IUpmpOrganizationService IUpmpOrganizationService;

    @Autowired
    private PDstTxnAuthCfgService pDstTxnAuthCfgService;


//    @RequiresPermissions("产品管理:支付通道管理")
    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public String index(HttpServletRequest request,PDstTxnAuthCfg pDstTxnAuthCfg) {
        String chnlOptFlag = request.getParameter("optFlag");
        String instId = request.getParameter("instId");
        String dstChannelId = request.getParameter("dstChannelId");
        //String feeCd = request.getParameter("feeCd");
        request.setAttribute("chnlOptFlag",chnlOptFlag);//通道信息管理传过来的操作类型
        request.setAttribute("instId",instId);
        request.setAttribute("dstChannelId",dstChannelId);

        return "admin/igas/pDstTxnAuthCfg/pDstTxnAuthCfg-index";
    }

    @RequiresPermissions("pDstChannel:info")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public List<PDstTxnAuthCfg> findByPage(HttpServletRequest request, PDstTxnAuthCfg pDstTxnAuthCfg) throws  RedpException{
        String instId = request.getParameter("instId");
        String msgDstId=request.getParameter("dstChannelId");
        String channelTxn = request.getParameter("channelTxn");
        List<PDstTxnAuthCfg> pDstTxnAuthCfgListByDstChannelId = pDstTxnAuthCfgService.findPDstTxnAuthCfgListByDstChannelId(instId, msgDstId, channelTxn);
        return pDstTxnAuthCfgListByDstChannelId;

    }
    @RequiresPermissions("pDstChannel:info")
    @RequestMapping(value = "/edit-tabs", method = RequestMethod.GET)
    @ResponseBody
    public PDstChannelInfo editTabs(HttpServletRequest request) throws RedpException{
        String chnlOptFlag = request.getParameter("chnlOptFlag");
        String optFlag = request.getParameter("optFlag");

        if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_VIEW.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)

        ){
            String instId = request.getParameter("instId");
            String dstChannelId = request.getParameter("dstChannelId");
            String channelTxn = request.getParameter("channelTxn");


            request.setAttribute("chnlOptFlag",chnlOptFlag);
            request.setAttribute("optFlag",optFlag);
            request.setAttribute("instId",instId);
            request.setAttribute("dstChannelId",dstChannelId);
            request.setAttribute("channelTxn",channelTxn);

            request.setAttribute("tabActive",0);
          PDstChannelInfo pDstChannelInfo = pDstChannelInfoService.findOne(instId,dstChannelId);
return pDstChannelInfo;
        }else {
            logger.error("不支持审核操作!");
            throw new RedpException("不支持审核操作！");
        }
    }

    @RequiresPermissions("pDstChannel:stop")
    @Log("停用")
//    @RequiresPermissions("产品管理:支付通道管理")
    @RequestMapping(value = "/changeStatus", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult changeStatus( @ModelAttribute("pDstTxnAuthCfg")PDstTxnAuthCfg entity,HttpServletRequest request) throws  RedpException {

        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();

        PDstTxnAuthCfg db = pDstTxnAuthCfgService.findOne(entity.getInstId(),entity.getMsgDstId(),entity.getChannelTxn());
        if(Common.isBlank(db)){
            logger.error("根据唯一索引没有找到指定数据！");
            throw new RedpException("没有找到指定数据！");
        }
        if(IgasYesOrNoEnum.Yes.getType().equals(db.getSupportFlag())
                || IgasYesOrNoEnum.No.getType().equals(db.getSupportFlag())){

            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(db.getInstId());

            String supportFlag = db.getSupportFlag();
            if (supportFlag.equals("Y")){
                db.setSupportFlag("N");
            }else {
                db.setSupportFlag("Y");
            }

            pDstTxnAuthCfgService.updatePDstTxnAuthCfg(db);
        }
        //TODO 添加实际业务操作
        return OperationResult.buildFailureResult("不支持的状态", result);
    }


    @RequiresPermissions("pDstChannel:info")
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    @ResponseBody
    public PDstTxnAuthCfg editShow(@ModelAttribute("pDstTxnAuthCfg")PDstTxnAuthCfg entity, HttpServletRequest request) throws RedpException {
        String optFlag = request.getParameter("optFlag");
        String chnlOptFlag = request.getParameter("chnlOptFlag");
        if (Common.isBlank(optFlag)) {
            logger.error("请求参数(optFlag)异常!");
            throw new RedpException("请求参数异常！");
        }

        String instId = request.getParameter("instId");
        if(Common.isBlank(instId)){
            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(instId);
            instId = user.getInstId();
            entity.setInstId(instId);
        }
        List<LabelValueBean> yesOrNo = Lists.newArrayList();
        yesOrNo.add(new LabelValueBean("是",IgasYesOrNoEnum.Yes.getType()));
        yesOrNo.add(new LabelValueBean("否",IgasYesOrNoEnum.No.getType()));
        request.setAttribute("yesOrNo",yesOrNo);

        List<LabelValueBean> accTypes = Lists.newArrayList();
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.ALL_ACCOUNT.getDesc(),SettleAccTypeEnum.ALL_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_DEBIT_ACCOUNT.getDesc(),SettleAccTypeEnum.INNER_DEBIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_CREDIT_ACCOUNT.getDesc(),SettleAccTypeEnum.INNER_CREDIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_BANKBOOK.getDesc(),SettleAccTypeEnum.INNER_BANKBOOK.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_INTERNAL_ACCOUNT.getDesc(),SettleAccTypeEnum.INNER_INTERNAL_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_PUBLIC_ACCOUNT.getDesc(),SettleAccTypeEnum.INNER_PUBLIC_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_DEBIT_ACCOUNT.getDesc(),SettleAccTypeEnum.OTHER_DEBIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_CREDIT_ACCOUNT.getDesc(),SettleAccTypeEnum.OTHER_CREDIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_BANKBOOK.getDesc(),SettleAccTypeEnum.OTHER_BANKBOOK.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_INTERNAL_ACCOUNT.getDesc(),SettleAccTypeEnum.OTHER_INTERNAL_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_PUBLIC_ACCOUNT.getDesc(),SettleAccTypeEnum.OTHER_PUBLIC_ACCOUNT.getType()));

        request.setAttribute("accTypes",accTypes);
        String dstChannelId = request.getParameter("dstChannelId");
        entity.setMsgDstId(dstChannelId);
        PDstChannelInfo pDstChannelInfo = pDstChannelInfoService.findOne(entity.getInstId(),entity.getMsgDstId());
        if (Common.isBlank(pDstChannelInfo)) {
            logger.error("根据唯一索引[{},{}]没有找到指定通道数据！",entity.getInstId(),entity.getMsgDstId());
            throw new RedpException("根据唯一索引没有找到指定通道数据！");
        }
        entity = pDstTxnAuthCfgService.findOne(entity.getInstId(),entity.getMsgDstId(),entity.getChannelTxn());
        if(Common.isNotBlank(entity.getChannelTxn())){

            if (Common.isBlank(entity)) {
                logger.info("根据唯一索引[instId:{},dstChannelId:{},channelTxn:{}]没有找到指定通道交易数据！", entity.getInstId(), entity.getMsgDstId(), entity.getChannelTxn());
                throw new RedpException("根据唯一索引[instId:"+entity.getInstId()+",dstChannelId:"+entity.getMsgDstId()+",channelTxn:"+entity.getChannelTxn()+"]没有找到指定通道交易数据！");
            }
            else{

                List<String> supportedAcctTypes = Lists.newArrayList();
                if("*".equals(entity.getSupportAcctType())){
//                    String type = SettleAccTypeEnum.ALL_ACCOUNT.getType();
//                    supportedAcctTypes.add(SettleAccTypeEnum.ALL_ACCOUNT.getType());
                    for ( LabelValueBean bean: accTypes) {
                        if (!bean.getValue().equals("*"))
                        supportedAcctTypes.add(bean.getValue());
                    }
                }else if(Common.isNotBlank(entity.getSupportAcctType())&&entity.getSupportAcctType().length()>=10){

                    String[] acctypes = entity.getSupportAcctType().split("");
                    for(int i=0;i<10;i++){
                        if(IgasYesOrNoEnum.Yes.getType().equals(acctypes[i])){
                            supportedAcctTypes.add(accTypes.get(i+1).getValue());
                        }
                    }
                }else{
                    logger.info("entity.getSupportAcctType() 值长度为{}，不符合规范",null==entity.getSupportAcctType()?0:entity.getSupportAcctType().length());
                }
                entity.setSupportAcctTypeList(supportedAcctTypes);
            }
        }else {
            entity.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        }

        entity.setSupportBeginTime(pDstChannelInfo.getBizStartTime());

        request.setAttribute("entity", entity);

        request.setAttribute("optFlag",optFlag);
        return  entity;
//        return "admin/igas/pDstTxnAuthCfg/pDstTxnAuthCfg-inputBasic";
    }

    @RequiresPermissions("pDstChannel:update")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult editSave(@ModelAttribute("pDstTxnAuthCfg")PDstTxnAuthCfg entity, HttpServletRequest request) {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        if ("".equals(entity.getSupportAcctType())||entity.getSupportAcctType().equals(null)){
            entity.setSupportAcctType("*");
        }
//        boolean save = pDstTxnAuthCfgService.save(entity);
        QueryWrapper<PDstTxnAuthCfg> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("inst_id", entity.getInstId());
        queryWrapper.eq("msg_dst_id", entity.getMsgDstId());
        queryWrapper.eq("channel_txn", entity.getChannelTxn());
            if (!entity.getSupportAcctType().equals("*"))
                entity.setSupportAcctType(pDstChannelInfoService.getSupportAcctType(entity.getSupportAcctType()));

         boolean save = pDstTxnAuthCfgService.saveOrUpdate(entity, queryWrapper);
//    	getEntityService().save(entity);
        //TODO 添加实际业务操作
        if (save==true){
            return OperationResult.buildSuccessResult("数据保存处理完成", result);
        }else {
            return OperationResult.buildSuccessResult("数据保存处理异常", result);
        }
    }

    @RequiresPermissions("pDstChannel:info")
    @RequestMapping(value = "/editTime", method = RequestMethod.GET)
    @ResponseBody
    public PDstTxnAuthCfg editTimeShow(@ModelAttribute("pDstTxnAuthCfg")PDstTxnAuthCfg entity, HttpServletRequest request)throws RedpException {

        if(Common.isBlank(entity.getInstId())){
            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(entity.getInstId());
            entity.setInstId(user.getInstId());
        }

        PDstChannelInfo pDstChannelInfo = new PDstChannelInfo();
        String dstChannelId = request.getParameter("dstChannelId");
        entity.setMsgDstId(dstChannelId);
        pDstChannelInfo = pDstChannelInfoService.findOne(entity.getInstId(),entity.getMsgDstId());
        if (Common.isBlank(pDstChannelInfo)) {
            logger.error("根据唯一索引[{},{}]没有找到指定通道数据！",entity.getInstId(),entity.getInstId());
            throw new RedpException("根据唯一索引[instId:"+entity.getInstId()+",dstChannelId:"+entity.getMsgDstId()+"]没有找到指定通道数据！");
        }

        PDstTxnAuthCfg db = pDstTxnAuthCfgService.findOne(entity.getInstId(),entity.getMsgDstId(),entity.getChannelTxn());
        if (Common.isBlank(db)) {
            logger.info("根据唯一索引[instId:{},dstChannelId:{},channelTxn:{}]没有找到指定通道交易数据！", entity.getInstId(), entity.getMsgDstId(), entity.getChannelTxn());
            throw new RedpException("根据唯一索引[instId:"+entity.getInstId()+",dstChannelId:"+entity.getMsgDstId()+",channelTxn:"+entity.getChannelTxn()+"]没有找到指定通道交易数据！");
        }

        db.setChannelTxn(entity.getChannelTxn());
        BeanUtils.copyProperties(db,entity);


   //     entity.setSupportBeginTime(pDstChannelInfo.getBizStartDate());

        entity.setSupportFlag(IgasYesOrNoEnum.Yes.getType());
        request.setAttribute("entity", entity);
  return  entity;
      //  return "admin/igas/pDstTxnAuthCfg/pDstTxnAuthCfg-inputTimeBasic";
    }


}
